package main

import "fmt"

//#link: https://leetcode-cn.com/problems/reverse-substrings-between-each-pair-of-parentheses/
func main() {
	str := "(u(love)i)"
	//s := reverse(str, 0, len(str))
	//fmt.Println(s)
	fmt.Println(reverseParentheses(str))
}

func reverseParentheses(s string) string {
	str := make([]byte, 0)
	stack := make([][]byte, 0)
	for i := 0; i < len(s); i++ {
		if s[i] == '(' {
			stack = append(stack, str)
			str = make([]byte, 0)
		} else if s[i] == ')' {
			//反转str
			for begin, end := 0, len(str); begin < end/2; begin++ {
				str[begin], str[end-begin-1] = str[end-begin-1], str[begin]
			}
			str = append(stack[len(stack)-1], str...)
			stack = stack[:len(stack)-1]
		} else {
			str = append(str, s[i])
		}
	}
	return string(str)
}

func reverse(s []byte, begin, end int) string {
	for i := begin; i < (end-begin)/2; i++ {
		s[i], s[end-i-1] = s[end-i-1], s[i]
	}

	return string(s)
}
